<template>
  <div class="cart">
    <div class="cart_nav">
      <div class="options">购物数量 {{ this.totalNums }}</div>
      <span @click="manager">{{ this.managerType ? "管理" : "取消" }}</span>
    </div>
    <div class="cart_list">
      <ul>
        <li v-for="cart in cartList" :key="cart.id">
          <van-checkbox
            v-model="cart.ischecked"
            @change="setCheckedStatus"
          ></van-checkbox>
          <!-- <img :src="cart.image" alt="" /> -->
          <div class="info">
            <p>{{ cart.storeName }}</p>
            <span>属性: {{ cart.suk }}</span>
            <div>
              <p>￥{{ cart.price }}</p>
              <div class="count">
                <span @click="setNums('minus', cart)">-</span>
                <input type="text" v-model="cart.cartNum" />
                <span @click="setNums('add', cart)">+</span>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="cart_order">
      <div class="co_left">
        <van-checkbox
          v-model="isAllCheck"
          @click="setAllChecked"
        ></van-checkbox>
        <!-- <van-checkbox v-model="isAllCheck"></van-checkbox> -->
        <p>全选({{ selectGoodsNums }})</p>
      </div>
      <div v-show="managerType" class="co_right">
        <p>总价: ￥{{ totalPrice }}</p>
        <button @click="setOrder">立即下单</button>
      </div>
      <div v-show="!managerType">
        <button @click="saveFavCart">收藏</button>
        <button @click="deleteCart">删除</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      totalNums: 0, // 购物车商品总数量
      managerType: true,
      cartList: [], // 购物车列表
      isAllCheck: true, // 全选
      totalPrice: 0, // 总价
      selectGoodsNums: 0, // 选中购物车商品数量
    };
  },
  created() {
    this.getCartList();
  },
  methods: {
    getCartList() {
      this.$axios
        .get(
          "https://apif.java.crmeb.net/api/front/cart/list?page=1&limit=20&isValid=true"
        )
        .then(({ data }) => {
          const carts = data.data.list;
          let nums = 0;
          carts.forEach(item => {
            item.ischecked = true; // 新增属性，记录每一个商品是否被选中。每个商品都需要一个独立的布尔值记录状态。
            nums += item.cartNum;
          });
          this.cartList = carts;
          this.totalNums = nums;
          this.selectGoodsNums = carts.length;
        });
    },
    manager() {
      this.managerType = !this.managerType;
    },
    setNums(type, cart) {
      const num = cart.cartNum;
      switch (type) {
        case "minus":
          if (num > 1) {
            this.setCartNums(cart.id, num - 1);
          } else alert("至少选择一件");
          break;
        case "add":
          this.setCartNums(cart.id, num + 1);
          break;
        default:
          break;
      }
    },
    setCheckedStatus(bool) {
      // console.log(bool); // 状态变化的新值
      this.isAllCheck = this.cartList.every(item => item.ischecked);
      this.selectGoodsNums = this.cartList.filter(
        goods => goods.ischecked
      ).length;
    },
    setAllChecked() {
      // console.log("全选:", this.isAllCheck);
      this.cartList.forEach(item => {
        item.ischecked = this.isAllCheck;
      });
    },
    setCartNums(id, num) {
      // this.$axios
      //   .post(`https://apif.java.crmeb.net/api/front/cart/num`, {
      //     id: id,
      //     number: num,
      //   })
      //   .then(({ data }) => {
      //     console.log(data);
      //   });
      this.$axios({
        url: "https://apif.java.crmeb.net/api/front/cart/num",
        method: "POST",
        params: {
          id: id,
          number: num,
        },
      }).then(({ data }) => {
        if (data.code == 200) {
          this.getCartList();
        }
      });
    },
    saveFavCart() {
      let favList = this.cartList.map(goods => {
        if (goods.ischecked) {
          return goods.productId;
        }
      });
      favList = favList.filter(ids => ids != null);

      this.$axios
        .post("https://apif.java.crmeb.net/api/front/collect/all", {
          category: "product",
          id: favList,
        })
        .then(({ data }) => {
          if (data.code == 200) {
            alert("收藏成功");
          }
        });
    },
    deleteCart() {
      let carts = this.cartList.filter(carts => carts.ischecked);
      let ids = carts.map(cart => cart.id).join(",");
      this.$axios
        .post(`https://apif.java.crmeb.net/api/front/cart/delete?ids=${ids}`)
        .then(({ data }) => {
          if (data.code == 200) {
            alert("删除成功");
            this.getCartList();
          }
        });
    },
    setOrder() {
      // 获取预下单订单号
      const options = this.cartList
        .map(cart => cart.ischecked && cart.id)
        .filter(res => res != false);

      const params = {
        preOrderType: "shoppingCart", //预下单类型。
        orderDetails: options.map(id => {
          return {
            shoppingCartId: id,
          };
        }), //准备下单的购物车id
      };
      this.$axios
        .post("https://apif.java.crmeb.net/api/front/order/pre/order", params)
        .then(({ data }) => {
          this.$router.push(`/preOrder?preOrderNo=${data.data.preOrderNo}`);
        });
    },
  },
  watch: {
    // isAllCheck(value) {
    //   this.cartList.forEach(item => {
    //     item.ischecked = value;
    //   });
    // },
    cartList: {
      handler(newList) {
        let price = 0;
        this.cartList.forEach(goods => {
          if (goods.ischecked) {
            price += goods.cartNum * goods.price;
          }
        });
        this.totalPrice = price;
      },
      deep: true, // 深度监听数据变化
    },
  },
};
</script>

<style lang="scss" scoped>
.cart {
  overflow: scroll;
  position: relative;
  height: calc(100vh - 81px);
  background-color: #333;
  color: white;
  .cart_nav {
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10px;
    box-sizing: border-box;
    border-bottom: 1px solid yellow;
  }
  .cart_list {
    height: calc(100vh - 181px);
    overflow-y: scroll;
    &::-webkit-scrollbar {
      display: none;
    }
    li {
      margin: 15px 10px;
      display: flex;
      justify-content: space-between;
      img {
        width: 80px;
        height: 80px;
      }
      .info {
        width: 200px;
        > p {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        > span {
          display: block;
          font-size: 12px;
          color: lightblue;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          margin: 10px 0;
        }
        > div {
          display: flex;
          justify-content: space-between;
          .count {
            display: flex;
            align-items: center;
            input {
              width: 10px;
              padding: 5px 10px;
              font-size: 14px;
              border: none;
              background-color: lightblue;
              margin: 0 10px;
              color: black;
            }
          }
        }
      }
    }
  }
  .cart_order {
    border-top: 1px solid yellow;
    background-color: #333;
    width: 100vw;
    position: absolute;
    bottom: 0;
    left: 0;
    height: 50px;
    display: flex;
    justify-content: space-between;
    padding: 0 10px;
    box-sizing: border-box;
    align-items: center;
    > div {
      display: flex;
      align-items: center;
      button {
        color: black;
        margin-left: 20px;
      }
    }
  }
}
</style>
